﻿using DongFangGuoKai.WCSPlatform.WebApi.Logs;
using SqlSugar;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    /// <summary>
    /// 清除日志
    /// </summary>
    public class LogClearHostService : BackgroundService
    {
        private readonly ILogger<LogClearHostService> logger;
        private readonly IServiceProvider provider;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="provider"></param>
        public LogClearHostService(ILogger<LogClearHostService> logger,IServiceProvider provider)
        {
            this.logger = logger;
            this.provider = provider;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(5000,stoppingToken);
            logger.LogInformation($"日志清除任务启动成功");
            while (!stoppingToken.IsCancellationRequested)
            {
                using var scope = provider.CreateScope(); // 获取作用域的DI
                var client = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();

                try
                {
                    // 获取当前日期
                    DateTime currentDate = DateTime.Now.Date;
                    // 计算需要删除的日期（当前日期的上个月）
                    DateTime targetDate = currentDate.AddMonths(-1);
                    // 计算需要删除的文件名
                    string targetFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Logs/allLog-{targetDate:yyyy-MM-dd}.log");
                    // 删除文件
                    var delFileLog = string.Empty;
                    if (File.Exists(targetFileName))
                    {
                        File.Delete(targetFileName);
                        delFileLog = $"文件-{targetFileName}";
                    }

                    // 开始数据库事务
                    client.Ado.BeginTran();

                    // 从数据库中删除指定日期之前的日志数据
                    var delDbLog=string.Empty;
                    var logList = client.Queryable<LogModel>().Where(log => log.Logged.Contains(targetDate.Date.ToString("yyyy/MM/dd"))).ToList();
                    if (client.Deleteable(logList).ExecuteCommand() > 0)
                    {
                        delDbLog = $"清除日志:{delFileLog},数据库条数-{logList.Count}";
                    }
                    if (!string.IsNullOrEmpty(delFileLog) || !string.IsNullOrEmpty(delDbLog))
                    {
                        logger.LogInformation(delFileLog + delDbLog);
                    }
                    
                    // 提交数据库事务
                    client.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    logger.LogError($"清除日志出现异常: {ex.Message}");
                    // 回滚数据库事务
                    client.Ado.RollbackTran();
                }

                // 等待一段时间再继续下一次循环
                await Task.Delay(TimeSpan.FromHours(24), stoppingToken); // 每隔一天执行一次
            }
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            logger.LogError($"日志清除任务异常停止");
            return base.StopAsync(cancellationToken);
        }

    }
}
